/**
 * @(#)BruchTaskManager.java 2017年6月1日
 * Copyright(C) 2017年6月1日 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.brush;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jsbd.boss.common.BaseThread;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.common.utils.StringUtils;

/**
 * 服务端刷任务公共类
 * @author <a href="mailto:zhouchao@zhexinit.com" >周超</a>
 * @version 1.0.0
 */
public class BruchTaskManager extends BaseThread{
	
	public static final Logger LOGGER = LoggerFactory.getLogger(BruchTaskManager.class);

	private static final String QUEUE_KEY="BRUCH_TASK_QUEUE_KEY";
	
	
	private static RedisClient<String,Object> redisClient;
	
	private int threadNum=10;
	
	private ExecutorService threadService;
	
	@Override
	public void start() {
		if(threadService==null){
			threadService=Executors.newFixedThreadPool(threadNum);
		}
		
		final BruchCommnTaskBean task=(BruchCommnTaskBean)redisClient.pollFromQueue(QUEUE_KEY);
		if(task==null||StringUtils.isBlank(task.getClassName())){
			return;
		}
		
		threadService.execute(new Runnable() {
			@Override
			public void run() {
				IBruchService service=SpringContextUtils.getBean(task.getClassName(), IBruchService.class);
				if(service==null){
					LOGGER.error("class [{}] not find",task.getClassName());
				}
				
				service.execute(task.getParam());
			}
		});
	}
	
	public static void addTask(BruchCommnTaskBean task){
		redisClient.putToQueue(QUEUE_KEY, task);
	}

	public static RedisClient<String, Object> getRedisClient() {
		return redisClient;
	}

	@Autowired
	public static void setRedisClient(RedisClient<String, Object> redisClient) {
		BruchTaskManager.redisClient = redisClient;
	}

	public int getThreadNum() {
		return threadNum;
	}

	public void setThreadNum(int threadNum) {
		this.threadNum = threadNum;
	}
    

}
